iT邦幫忙

2025 iThome 鐵人賽

DAY 27
0
Build on AWS

從零到雲端:AWS 開發之路系列 第 27

Day27 我的回憶清單 ─ 建立「歷史日記」畫面

  • 分享至 

  • xImage
  •  

昨天我們將回憶的頁面與新增的畫面放在一起,今天我們把它們分開,將歷史畫面與新增畫面分隔開來,首先先在資料夾中創立history.html

HTML 結構

標題,顯示在頁面最上方

<h1>歷史回憶</h1>

用來放「歷史回憶卡片」的容器

<div id="history"></div>

提供回首頁的連結

<a href="index.html">⬅ 回到首頁</a>

CSS 樣式

整體頁面

body 背景顏色我設為淡灰 (#f0f4f8),字體設定為常用的系統字型

標題

h1 文字置中,顏色深灰

卡片樣式(.diary-card)

  • 固定寬高:220px × 280px
  • 白色背景,圓角、陰影
  • 卡片內部排列為垂直方向 (flex-direction: column)
  • 文字和圖片置中

圖片 (.diary-card img)

限制最大寬高,保持比例
圓角 8px

文字 (.diary-text)

中小字,居中對齊
超出部分會隱藏 (overflow: hidden)

日期 (.diary-title)

粗體、置中顯示

目前的成果看起來像這樣:
https://ithelp.ithome.com.tw/upload/images/20251009/20169251oHexZFKTMy.png

JavaScript 運作

1. 抓取 DOM 元素:用來把日記卡片加進頁面

const historyDiv = document.getElementById('history');

2. 取得日記資料

localStorage 取出 diaries 資料(JSON 格式)
若沒有資料,回傳空陣列 []

const diaries = JSON.parse(localStorage.getItem('diaries') || '[]');

3. 建立卡片

對每一筆日記建立一張卡片
卡片包含:

  1. 圖片 (entry.image)
  2. 日期 (entry.timestamp)
  3. 文字內容 (entry.text)

把卡片加入到 #history 容器

diaries.forEach(entry => {
  const card = document.createElement('div');
  card.className = 'diary-card';

  const img = document.createElement('img');
  img.src = entry.image;

  const titleDiv = document.createElement('div');
  titleDiv.className = 'diary-title';
  const dateObj = new Date(entry.timestamp);
  titleDiv.textContent = dateObj.toLocaleDateString();

  const textDiv = document.createElement('div');
  textDiv.className = 'diary-text';
  textDiv.textContent = entry.text;

  card.appendChild(img);
  card.appendChild(titleDiv);
  card.appendChild(textDiv);

  historyDiv.appendChild(card);
});

index.html

在首頁新增跳轉頁面的按鈕:
id="historyBtn":給這個按鈕設定一個唯一的識別名稱
按鈕上顯示的文字是 「📖 查看歷史回憶」

<button id="historyBtn">📖 查看歷史回憶</button>

javaScript 部分

下面這段程式碼是處理它的功能,把按鈕抓出來(透過 id),讓 JavaScript 能夠監聽它的事件

const historyBtn = document.getElementById('historyBtn');

接著是主要功能:
1. 監聽事件:
當使用者點擊 historyBtn 按鈕時(click 事件),就執行箭頭函式裡的內容。
2. 切換頁面:
window.location.href = 'history.html';這行會把使用者導向到名為 history.html 的頁面

historyBtn.addEventListener('click', () => {
  window.location.href = 'history.html';
});

index.html的頁面就會變成這樣:
https://ithelp.ithome.com.tw/upload/images/20251009/20169251G9g9zMW4nC.png


上一篇
Day26 文字與影像的結合 — Base64 儲存日記到 localStorage
下一篇
Day28 重返昨日 ─ 點擊卡片查看完整日記
系列文
從零到雲端:AWS 開發之路30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言